package blue.http.core.filter;

import blue.http.core.annotation.Filter;
import blue.http.core.message.HttpRequest;
import blue.http.core.message.HttpResponse;

import java.util.UUID;

/**
 * @author Jin Zheng
 * @since 1.0 2020-01-08
 */
@Filter(filters = "/**", order = 1)
public class SessionCookieFilter implements HttpFilter {
	public static final String SESSION = "session";

	private String sessionKey;

	public SessionCookieFilter() {
		this(SESSION);
	}

	public SessionCookieFilter(String sessionKey) {
		this.sessionKey = sessionKey;
	}

	@Override
	public boolean preHandle(HttpRequest request, HttpResponse response) throws Exception {
		String session = request.getCookie(sessionKey);
		if (session == null || session.isEmpty()) {
			String value = UUID.randomUUID().toString();
			response.getCookie().put(sessionKey, value);
		}
		return true;
	}

}
